#!/usr/bin/env node

const http = require('http'),
      log = console.log,
      items = [];

function genPage(){
  let html = `<!DOCTYPE html>
 <html lang="en">
<head>
  <meta charset="UTF-8">
  <title>todo list</title>
</head>
<body>
  <h1>TODO List</h1>
  <form method="GET" action="/">
    <input type="text" name="item">
    <input type= "submit" value= "submit">
  </form>
  <ul>%</ul>
</body>
</html>`;
  
  const dom = items.map(item=>`<li>${item}</li>`).join('');
  html = html.replace('%',dom);
  return html;
}

//测试genPage()是否能运行,items=['abc','def']
//log(genPage());
//process.exit();

http.createServer((req,res)=>{
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log();

  const url = new URL(req.url,`http://${req.headers.host}`),
  pathname = url.pathname,
  item = url.searchParams.get('item');

  if(pathname === '/'){
    if(item !== null && item !== ''){
      items.push(item);
    }
    res.end(genPage());
  }else{
    res.statusCode = 404;
    res.end('Resource not found！')  
  }
}).listen(8080);
